import _config from './config.js'

const common_utils = require('../common_utils.js')

/**
 * 公共请求
 * @param {String} url 地址
 * @param {Object} data 提交的参数
 * @param {Boolean} showLoading 是否显示加载中字样
 * @param {Boolean} contentType 请求头的Content-Type 默认就好了
 * @param {Boolean} showToast 错误提示显示吐司还是弹窗，默认true显示吐司

 */
const request = (url, data, showLoading) => {
  return new Promise((resolve, reject) => {
    if (showLoading) {
      wx.showLoading({
        title: '加载中',
      })
    }
    data.openid = wx.getStorageSync('open_id')
    data.sessionKey = wx.getStorageSync('session_key')
    data.user_id = wx.getStorageSync('user_id')
    wx.request({
      url: url,
      method: "POST",
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (showLoading) {
          wx.hideLoading()
        }
        if (res.statusCode == 200) {
          let code = res.data.code
          if (code == 0) {
            // 接口成功
            resolve(res.data)
          } else if (code == 705) { //未登录
            reject()
            getApp().globalData.loginFlag = false
            let currentPage = getCurrentPages()[getCurrentPages().length - 1].route
            if (currentPage == 'pages/login/login') {
              return;
            } else {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
          } else {
            common_utils.showToast(res.data.msg)
          }
        } else if (res.statusCode == 404) {
          common_utils.showToast("页面开小差，刷新试试")
          reject()
        } else {
          common_utils.showToast("系统繁忙，请稍后再试")
          reject()
        }
      },
      fail(error) {
        if (showLoading) {
          wx.hideLoading()
        }
        common_utils.showToast("网络断开，请检查网络")
        reject(error)
      }
    })
  })
}





module.exports = {
  request,
}